/**
 * JAVACC DEMO 1.0
 */
package com.apache.passport.controller;

import com.apache.api.manager.BaseManager;
import com.apache.api.vo.ParamsVo;
import com.apache.api.vo.ResultEntity;
import com.apache.api.vo.ResultMsg;
import com.apache.cache.util.Validator;
import com.apache.passport.common.DesUtils;
import com.apache.passport.common.PassPortConst;
import com.apache.passport.common.PassportHelper;
import com.apache.passport.entity.LonErrToken;
import com.apache.passport.entity.UctUser;
import com.apache.passport.manager.UctUserManager;
import com.apache.passport.service.CacheHelper;
import com.apache.tools.MD5Utils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * description:  用户注册,密码更新操作<p>
 * 密码修改页面有两个:
 * (1):http://localhost:8089/passport/passport/reg/find-pwd.action
 * (2):http://localhost:8089/passport/passport/reg/passport-mn.action
 *
 * @author Hou Dayu 创建时间：2016-12-22
 */
@Controller
@RequestMapping({ "/passport/reg/" })
public class RegAction extends SsoBaseAction<UctUser> {

    @Autowired
    UctUserManager uctUserManager;

    private final String REG_PAGE = getPrefix() + "register";

    private final String UPDATE_PWD = getPrefix() + "find-pwd";

    private final String GETPASS_INDEX = getPrefix() + "getpassindex";

    private final String EMAIL_INDEX = getPrefix() + "emailindex";

    private final String UPDATE_PASSWORD = getPrefix() + "update-pwd";

    /**
     * description:  用户注册,所有项需要校验是否已经存在
     *
     * @param request
     * @param response
     * @return
     */
    @RequestMapping({ "reg.action" })
    @ResponseBody
    public ResultMsg reg(HttpServletRequest request, HttpServletResponse response, String userEname,
            String userPass, String mobile, String email, String userCname) {
        ResultMsg rmsg = new ResultMsg("F", "注册失败");

        if (Validator.isNull(userEname)) {
            rmsg.setFlag("F");
            rmsg.setMsg("用户名不能为空");
            return rmsg;
        }

        if (Validator.isNull(userCname)) {
            rmsg.setFlag("F");
            rmsg.setMsg("姓名不能为空");
            return rmsg;
        }

        if (Validator.isNull(userPass)) {
            rmsg.setFlag("F");
            rmsg.setMsg("密码不能为空");
            return rmsg;
        }

        if (Validator.isNull(mobile)) {
            rmsg.setFlag("F");
            rmsg.setMsg("手机号不能为空");
            return rmsg;
        }

        if (Validator.isNull(email)) {
            rmsg.setFlag("F");
            rmsg.setMsg("邮箱不能为空");
            return rmsg;
        }

        if (!PassportHelper.getInstance().emailFormat(email)) {
            rmsg.setFlag("F");
            rmsg.setMsg("邮箱格式不正确");
            return rmsg;
        }

        if (!PassportHelper.getInstance().mobileFormat(mobile)) {
            rmsg.setFlag("F");
            rmsg.setMsg("手机号格式不正确");
            return rmsg;
        }
        ParamsVo<UctUser> vo = new ParamsVo();
        vo.setMethodKey("chkEname");
        vo.setParams("userEname", userEname);
        ResultEntity result = (ResultEntity) uctUserManager.execute(vo);
        if ("F".equals(result.getEntity())) {
            rmsg.setFlag("F");
            rmsg.setMsg("该用户名已被注册");
            return rmsg;
        }

        vo.setMethodKey("chkEmail");
        vo.setParams("email", email);
        result = (ResultEntity) uctUserManager.execute(vo);
        if ("F".equals(result.getEntity())) {
            rmsg.setFlag("F");
            rmsg.setMsg("邮箱已被注册");
            return rmsg;
        }

        vo.setMethodKey("chkMobile");
        vo.setParams("mobile", mobile);
        result = (ResultEntity) uctUserManager.execute(vo);
        if ("F".equals(result.getEntity())) {
            rmsg.setFlag("F");
            rmsg.setMsg("手机号已被注册");
            return rmsg;
        }
        UctUser user = new UctUser();
        user.setUserEname(userEname);
        user.setUserEname(userEname);
        user.setUserPass(userPass);
        user.setMobile(mobile);
        user.setEmail(email);
        //2015年2月26日09:41:17 添加用户中文名称
        user.setUserCname(userCname);
        //2015年1月28日16:01:23 修改 0为停用 ,1为启用
        user.setUserStatus(1);
        user.setCreateTime(PassportHelper.getInstance().sysNowDateTypeInt());
        user.setRegIp(request.getRemoteAddr());
        //2015年1月28日16:01:09 添加 否则uc无法查看
        user.setDelStatus("F");

        vo = this.getParamsVo(request, user);
        vo.setObj(user);
        String rtn = uctUserManager.saveInfo(vo);
        if (!Validator.isNull(rtn)) {
            rmsg.setFlag("T");
            rmsg.setMsg("注册成功!");
        }
        return rmsg;
    }

    /**
     * description:  更新密码
     *
     * @param request
     * @param response
     * @param userEname 用户名
     * @param userPass 旧密码
     * @param mobile 手机号
     * @param email 邮箱
     * @param newPass 新密码
     * @return
     */
    @RequestMapping({ "update-pwd.action" })
    @ResponseBody
    public ResultMsg uodatePwd(HttpServletRequest request, HttpServletResponse response,
            String userEname, String userPass, String mobile, String email, String newPass) {
        ResultMsg rmsg = new ResultMsg("F", "密码修改失败");

        if (!PassportHelper.getInstance().emailFormat(email)) {
            rmsg.setFlag("F");
            rmsg.setMsg("邮箱格式不正确");
            return rmsg;
        }

        if (!PassportHelper.getInstance().mobileFormat(mobile)) {
            rmsg.setFlag("F");
            rmsg.setMsg("手机号格式不正确");
            return rmsg;
        }

        UctUser user = new UctUser();
        user.setUserEname(userEname);
        user.setUserPass(userPass);
        user.setMobile(mobile);
        user.setEmail(email);
        user.setUserStatus(0);
        ParamsVo<UctUser> vo = this.getParamsVo(request, null);
        vo.setParams("newPass", newPass);
        vo.setMethodKey("updatePwd");
        vo.setParams("userEname", userEname);
        vo.setParams("userPass", userPass);
        vo.setParams("mobile", mobile);
        vo.setParams("email", email);
        vo.setParams("remoteIp", request.getRemoteAddr());

        ResultEntity result = (ResultEntity) uctUserManager.execute(vo);
        if ("T".equals(result.getEntity())) {
            rmsg.setFlag("T");
            rmsg.setMsg(result.getMessage());
        } else {
            rmsg.setFlag("F");
            rmsg.setMsg(result.getMessage());
        }
        return rmsg;
    }

    /**
     * description:  更新密码
     *
     * @param request
     * @param response
     * @param userEname
     * @param userPass
     * @param newPass
     * @return
     */
    @RequestMapping({ "update-pwd-view.action" })
    @ResponseBody
    public ResultMsg uodatePwd(HttpServletRequest request, HttpServletResponse response,
            String userEname, String userId, String userPass, String newPass) {
        ResultMsg rmsg = new ResultMsg("F", "密码修改失败");
        ParamsVo<UctUser> vo = this.getParamsVo(request, null);

        userEname = DesUtils.getInstance().decrypt(userEname);

        UctUser user = new UctUser();
        user.setUserEname(userEname);
        user.setUserPass(userPass);
        user.setUserStatus(0);
        user.setUserId(userId);

        vo.setParams("newPass", newPass);
        vo.setMethodKey("updatePwd");
        vo.setParams("userId", userId);
        vo.setParams("userEname", userEname);
        vo.setParams("userPass", userPass);
        vo.setParams("remoteIp", request.getRemoteAddr());

        ResultEntity result = (ResultEntity) uctUserManager.execute(vo);
        if ("T".equals(result.getEntity())) {
            rmsg.setFlag("T");
            rmsg.setMsg(result.getMessage());
        } else {
            rmsg.setFlag("F");
            rmsg.setMsg(result.getMessage());
        }
        return rmsg;
    }

    /**
     * description:  验证用户名是否唯一
     *
     * @param request
     * @param response
     * @param userEname
     * @return
     */
    @RequestMapping("chkEname.action")
    @ResponseBody
    public ResultMsg chkEname(HttpServletRequest request, HttpServletResponse response,
            String userEname) {
        ResultMsg rmsg = new ResultMsg("F", "用户名已存在");
        ParamsVo<UctUser> vo = new ParamsVo<UctUser>();
        vo.setMethodKey("chkEname");
        vo.setParams("userEname", userEname);
        ResultEntity result = (ResultEntity) uctUserManager.execute(vo);
        if ("T".equals(result.getEntity())) {
            rmsg.setFlag("T");
            rmsg.setMsg("用户不存在");
        } else {
            rmsg.setFlag("F");
            rmsg.setMsg("用户已存在");
        }
        return rmsg;
    }

    /**
     * description:  用户名校验(密码修改2)
     *
     * @param request
     * @param response
     * @param userEname
     * @return
     */
    @RequestMapping("chkuEname2Email.action")
    @ResponseBody
    public ResultMsg chkEname2Email(HttpServletRequest request, HttpServletResponse response,
            String userEname) {
        ResultMsg rmsg = new ResultMsg("F", "用户名不存在");
        ParamsVo<UctUser> vo = new ParamsVo<UctUser>();
        vo.setMethodKey("chkEnameGetObject");
        vo.setParams("userEname", userEname);
        ResultEntity result = (ResultEntity) uctUserManager.execute(vo);
        Object obj = result.getEntity();
        try {

            if (!Validator.isEmpty(obj)) {//注意F和T的使用
                if (obj instanceof UctUser) {
                    rmsg.setFlag("T");
                    rmsg.setMsg("用户查询成功");
                    UctUser user = (UctUser) obj;

                    String uEmail = user.getEmail();//.substring(0, 3)
                    StringBuilder sb = new StringBuilder();
                    if (uEmail.length() > 5) {
                        String[] arr = uEmail.split("@");
                        sb.append(arr[0].substring(0, arr[0].length() / 2));
                        sb.append("***");
                        sb.append(arr[0].substring(arr[0].length() - 1, arr[0].length()));
                        sb.append("@");
                        sb.append(arr[1]);
                    }
                    request.getSession().setAttribute("userEname",
                            DesUtils.getInstance().encrypt(user.getUserEname()));
                    request.getSession().setAttribute("userEmail",
                            DesUtils.getInstance().encrypt(user.getEmail()));
                    request.getSession().setAttribute("uEmail", sb.toString());
                    request.getSession().setAttribute("userId", user.getUserId());
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return rmsg;
    }

    /**
     * description:  校验邮箱唯一性
     *
     * @param request
     * @param response
     * @return
     */
    @RequestMapping("chkEmail.action")
    @ResponseBody
    public ResultMsg chkEmail(HttpServletRequest request, HttpServletResponse response,
            String email) {
        ResultMsg rmsg = new ResultMsg("F", "邮箱已存在");
        ParamsVo<UctUser> vo = new ParamsVo<UctUser>();
        vo.setMethodKey("chkEmail");
        vo.setParams("email", email);
        ResultEntity result = (ResultEntity) uctUserManager.execute(vo);
        if ("T".equals(result.getEntity())) {
            rmsg.setFlag("T");
            rmsg.setMsg("邮箱可注册");
        }
        return rmsg;
    }

    /**
     * description:  验证密码是否正确
     *
     * @param request
     * @param response
     * @return
     */
    @RequestMapping("chkPass.action")
    @ResponseBody
    public ResultMsg chkPass(HttpServletRequest request, HttpServletResponse response,
            String userEname, String userPass) {
        UctUser user = new UctUser();
        user.setUserEname(userEname);
        ResultMsg rmsg = new ResultMsg("F", "密码不正确");
        ParamsVo<UctUser> vo = new ParamsVo<UctUser>();
        vo.setObj(user);
        vo.setMethodKey("chkPass");
        vo.setParams("userEname", userEname);
        vo.setParams("userPass", MD5Utils.MD5(userPass));
        ResultEntity result = (ResultEntity) uctUserManager.execute(vo);
        if ("T".equals(result.getEntity())) {
            rmsg.setFlag("T");
            rmsg.setMsg("密码正确");
        }
        return rmsg;
    }

    @RequestMapping("chkPwd.action")
    @ResponseBody
    public ResultMsg chkPwd(HttpServletRequest request, HttpServletResponse response,
            String userEname, String userPass) {
        ResultMsg rmsg = new ResultMsg("F", "用户名不存在或密码错误");
        ParamsVo<UctUser> vo = new ParamsVo<UctUser>();
        if (Validator.isNull(userEname)) {
            rmsg.setMsg("用户名不能为空");
            return rmsg;
        }
        if (Validator.isNull(userPass)) {
            rmsg.setMsg("密码不能为空");
            return rmsg;
        }
        UctUser user = new UctUser();
        user.setUserEname(userEname);
        String remoteIp = request.getRemoteAddr();
        String tokenId = Validator.generate() + request.getSession().getId();
        vo.setParams("remoteIp", remoteIp);
        vo.setParams("sessionId", request.getSession().getId());
        vo.setParams("tokenId", tokenId);
        vo.setParams("userEname", user.getUserEname());
        vo.setParams("userPass", MD5Utils.MD5(userPass));
        vo.setObj(user);
        vo.setMethodKey("chkPwd");
        vo.setParams("userEname", userEname);
        vo.setParams("userPass", MD5Utils.MD5(userPass));
        ResultEntity result = (ResultEntity) uctUserManager.execute(vo);
        if ("T".equals(result.getEntity())) {
            rmsg.setFlag("T");
            rmsg.setMsg("密码正确");
        } else {
            //插件中存了错误次数,则在此判断
            LonErrToken token = PassPortConst.getLonErrToken(remoteIp, user.getUserEname());
            if (!Validator.isEmpty(token)) {
                String errCount = token.getLoginCount();
                String mim = token.getMim();
                int count = Integer.parseInt(errCount);
                String[] params = { mim };
                if (3 == count) {
                    rmsg.setMsg(PassportHelper.getInstance()
                            .getMessage(request, "login_err_3", params, ""));
                } else if (6 == count) {
                    rmsg.setMsg(PassportHelper.getInstance()
                            .getMessage(request, "login_err_6", params, ""));
                } else if (9 == count) {
                    rmsg.setMsg(PassportHelper.getInstance()
                            .getMessage(request, "login_err_9", params, ""));
                } else if (12 == count) {
                    rmsg.setMsg(PassportHelper.getInstance()
                            .getMessage(request, "login_err_12", params, ""));
                }
            }
        }
        return rmsg;
    }

    /**
     * description:  校验手机号唯一性
     *
     * @param request
     * @param response
     * @return
     */
    @RequestMapping("chkMobile.action")
    @ResponseBody
    public ResultMsg chkMobile(HttpServletRequest request, HttpServletResponse response,
            String mobile) {
        ResultMsg rmsg = new ResultMsg("F", "手机号已存在");
        ParamsVo<UctUser> vo = new ParamsVo<UctUser>();
        vo.setMethodKey("chkMobile");
        vo.setParams("mobile", mobile);
        ResultEntity result = (ResultEntity) uctUserManager.execute(vo);
        if ("T".equals(result.getEntity())) {
            rmsg.setFlag("T");
            rmsg.setMsg("手机号可注册");
        } else {
            rmsg.setFlag("F");
            rmsg.setMsg("该手机号已被注册");
        }
        return rmsg;
    }

    /**
     * description:  发送邮箱验证码
     *
     * @param request
     * @param response
     * @return
     */
    @RequestMapping("snd-email.action")
    @ResponseBody
    public ResultMsg snd(HttpServletRequest request, HttpServletResponse response,
            String userEmail) {
        ResultMsg rmsg = new ResultMsg("F", "发送失败");
        ParamsVo<UctUser> vo = new ParamsVo<UctUser>();
        String email = DesUtils.getInstance().decrypt(userEmail);
        vo.setMethodKey("sndEmail");
        vo.setParams("userEmail", email);
        ResultEntity result = (ResultEntity) uctUserManager.execute(vo);
        if (result != null) {
            String obj = (String) result.getEntity();
            if (!"F".equals(obj)) {
                CacheHelper.getInstance().getCache("randNum")
                        .createCacheObject(request.getSession().getId(), obj);
                rmsg.setFlag("T");
                rmsg.setMsg("验证码发送成功");
            } else {
                rmsg.setMsg(result.getMessage());
            }
        }
        return rmsg;
    }

    /**
     * description:  验证码校验
     *
     * @param request
     * @param response
     * @return
     */
    @RequestMapping("checkRandNum.action")
    @ResponseBody
    public ResultMsg checkRandNum(HttpServletRequest request, HttpServletResponse response,
            String checkNum) {
        ResultMsg rmsg = new ResultMsg("F", "验证码错误");
        String checkNumer = (String) CacheHelper.getInstance().getCache("randNum")
                .getCacheCloneByKey(request.getSession().getId());
        if (Validator.isNull(checkNum)) {
            rmsg.setMsg("验证码不能为空");
            return rmsg;
        }
        if (Validator.isNull(checkNumer)) {
            rmsg.setMsg("您的验证码已失效");
            return rmsg;
        }
        if (checkNum.equals(checkNumer)) {
            rmsg.setFlag("T");
            rmsg.setMsg("验证成功");
            CacheHelper.getInstance().getCache("randNum")
                    .removeCacheObject(request.getSession().getId());
            return rmsg;
        }
        return rmsg;
    }

    /**
     * description:  跳转至注册页面
     *
     * @param request
     * @return
     */
    @RequestMapping({ "passport-reg.action" })
    public ModelAndView initList(HttpServletRequest request) {
        ModelAndView view = new ModelAndView(REG_PAGE);
        return view;
    }

    /**
     * description:  跳转至确认账户界面
     *
     * @param request
     * @return
     */
    @RequestMapping({ "passport-mn.action" })
    public ModelAndView initMn(HttpServletRequest request) {
        ModelAndView view = new ModelAndView(GETPASS_INDEX);
        return view;
    }

    /**
     * description:  跳转至发送邮件界面
     *
     * @param request
     * @return
     */
    @RequestMapping({ "passport-email.action" })
    public ModelAndView initEm(HttpServletRequest request) {
        ModelAndView view = new ModelAndView(EMAIL_INDEX);
        return view;
    }

    /**
     * description:  跳转到修改密码页面
     *
     * @param request
     * @return
     */
    @RequestMapping({ "find-pwd.action" })
    public ModelAndView udatePwd(HttpServletRequest request) {
        ModelAndView view = new ModelAndView(UPDATE_PWD);
        return view;
    }

    /**
     * description:  跳转到更新密码界面2
     *
     * @param request
     * @return
     */
    @RequestMapping({ "update-pwd-page.action" })
    public ModelAndView updatePwd(HttpServletRequest request) {
        ModelAndView view = new ModelAndView(UPDATE_PASSWORD);
        return view;
    }

    @Override
    protected Object data(HttpServletRequest httpservletrequest, String s, String s1) {
        return null;
    }

    @Override
    protected BaseManager<UctUser> getBaseManager() {

        return null;
    }

    @Override
    protected String getPrefix() {

        return "/passport/passport-";
    }

}
